package carassius.BLL;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author siebz0r
 */
public final class Settings
{
	private final static File _settings;
	private static boolean readable;
	private static boolean writable;

	static
	{
		StringBuilder sb = new StringBuilder(System.getProperty("user.home"));
		sb.append("/.carassius/user.properties");
		_settings = new File(sb.toString());
		readable = true;
		writable = true;
	}

	public static File getSettingsFile()
	{
		return _settings;
	}

	public static String getSetting(String name)
	{
		FileInputStream fis = null;
		String outp = null;
		if (readable)
		{
			try
			{
				Properties properties = new Properties();
				fis = new FileInputStream(_settings);
				properties.load(fis);
				outp = properties.getProperty(name);
			}
			catch (FileNotFoundException ex)
			{
				readable = false;
			}
			catch (IOException ex)
			{
				readable = false;
			}
			finally
			{
				try
				{
					if (fis != null)
					{
						fis.close();
					}
				}
				catch (IOException ex)
				{
					System.out.println("Could not close file input streamer!");
				}
			}
		}
		return outp;
	}

	public static void setSetting(String name, String value)
	{
		if (readable && writable)
		{
			FileOutputStream fos = null;
			try
			{
				Properties properties = new Properties();
				fos = new FileOutputStream(_settings);
				properties.setProperty(name, value);
				properties.store(fos, null);
			}
			catch (IOException ex)
			{
				writable = false;
			}
			finally
			{
				try
				{
					if (fos != null)
					{
						fos.close();
					}
				}
				catch (IOException ex)
				{
					System.out.println("Could not close file output streamer!");
				}
			}
		}
	}

	public static void setSetting(String name, Boolean value)
	{
		setSetting(name, value.toString());
	}

	public static Boolean getSettingAsBoolean(String name)
	{
		return Boolean.valueOf(getSetting(name));
	}
}
